/*
package com.luoc.base.service.impl;


import com.alibaba.fastjson.JSON;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;


*/
/**
 * @Author: luoc
 * @Date: 2019/7/16 10:42
 * <p>
 * 留言记录
 * @param mid
 * <p>
 * $three_ranks = Db::name('guild_week_rank')->order('id desc')->value('three_ranks');
 * $crown = explode(',', $three_ranks);
 * $keys = array_search($mid, $crown);
 * $keys = (false === $keys) ? 0 : ($keys + 1) . ($keys + 1);
 * <p>
 * $three_ranks = Db::name('guild_week_rank')->order('id desc')->value('three_ranks');
 * $crown = explode(',', $three_ranks);
 * $keys = array_search($mid, $crown);
 * $keys = (false === $keys) ? 0 : ($keys + 1) . ($keys + 1);
 * <p>
 * $three_ranks = Db::name('guild_week_rank')->order('id desc')->value('three_ranks');
 * $crown = explode(',', $three_ranks);
 * $keys = array_search($mid, $crown);
 * $keys = (false === $keys) ? 0 : ($keys + 1) . ($keys + 1);
 *//*

@Service("wsUserService")
@Slf4j
public class wsUserServiceImpl implements wsUserService {


    @Autowired
    UserMapper userMapper;

    @Autowired
    GuildBannerMapper guildBannerMapper;

    @Autowired
    GuildWeekRankMapper guildWeekRankMapper;

    @Autowired
    MaterialMapper materialMapper;

    @Autowired
    GuildSpeakerMapper guildSpeakerMapper;

    @Autowired
    GuildSupperSpeakerCountMapper guildSupperSpeakerCountMapper;

    @Autowired
    GiftLogCountMapper giftLogCountMapper;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    GuildService guildService;
   @Value("deceased.mids")
    private String[] deceasedMids;

    @Override
    public Result bindUser(ChatMsg msg, Channel channel) {
        if (StringUtils.isEmpty(msg.getSenderId())){
            return Result.error("参数异常");
        }
        // 用户id与channel 绑定
        UserChannelRel.put(msg.getSenderId(), channel);
        log.info("senderId:{},channelId:{}",msg.getSenderId(),channel.id().asShortText());
        UserChannelRel.output();
       //String uid = OpenIdUtils.analysisOpenid(msg.getSenderId());
        String uid = "46";
        if (StringUtils.isNumeric(uid)){
             User user = userMapper.selectUserByUid(Integer.valueOf(uid));
            redisUtils.set(channel.id().asLongText(),user);
        }else {
            return Result.error("绑定失败");
        }
        return Result.ok(null);
    }

    @Override
    public Result rebindUser() {
         return null;
    }

    @Override
    public void login(ChatMsg msg, Channel channel) {
        if (StringUtils.isEmpty(msg.getMid())){
             return;
        }
        // 退出旧公会
        String oldMid = GuildChannelRel.userGuild.get(msg.getSenderId());
        if (oldMid !=null){
            GuildChannelRel.manager.get(oldMid).remove(channel);
        }
        // 加入新公会
        GuildChannelRel.put(msg.getSenderId(),msg.getMid(),channel);

        Map<String,Object> resultMap = new HashMap<>();

        // 互动消息
        if (msg.getMid().contains("message")){
            resultMap.put("type","first");
            List<Map<String,Object>> guildList = guildService
                    .getFlowerChangeListFromRedis(msg.getMid()
                    .replace("message",""));
            resultMap.put("data",guildList);
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(resultMap)));
        }

        //公会留言
        int mid = Integer.valueOf(msg.getMid());
        if (mid > 0){
            resultMap.put("type","news");
            resultMap.put("data",getWordMsg(msg.getMid()));
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(resultMap)));
        }

    }

    */
/**
 *  留言记录
 * @param mid
 *//*

    private  List<Map<String,Object>> getWordMsg(String mid){
        List<Map<String,Object>> chatLogList  = guildService.getGuildMsgListFromRedis(mid);
        if (chatLogList == null){
             chatLogList = guildService.getGuildMsgListFromRedis(mid);
        }
        if (chatLogList == null){
             chatLogList = new ArrayList();
        }else{
             //倒序
             Collections.reverse(chatLogList);
        }
        String day = DateUtils.format(new Date(),"YMMd");
        Map<String,Object> paranMap = new HashMap<>();
        paranMap.put("mid",mid);
        paranMap.put("day",day);
        Integer isBirthday = guildBannerMapper.getIsBirthday(paranMap);

        int keys = 0;
        String keyString = "" ;
        List rankList = new ArrayList();
        if ( isBirthday !=null && isBirthday > 0 ){
            keys = 44;
        }else {
            String threeRanks = guildWeekRankMapper.getInfoForWs();
            String[] ranks = threeRanks.split(",");
            // 要优化看看php源代码把
            */
/**
 * $three_ranks = Db::name('guild_week_rank')->order('id desc')->value('three_ranks');
 * $crown = explode(',', $three_ranks);
 * $keys = array_search($mid, $crown);
 * $keys = (false === $keys) ? 0 : ($keys + 1) . ($keys + 1);
 *//*

             rankList = Arrays.asList(ranks);
            for (int i=0;i< ranks.length;i++){
                 if (mid == ranks[i]){
                       keys = i;
                 }
            }
            if (rankList.contains(mid)){
                keyString = keys + 1 + "" + keys +1;
            }else {
                keys =0;
            }
        }

        if (chatLogList.size() > 0){
            for (Map<String,Object> map: chatLogList) {
                if (rankList.contains(mid)){
                    map.put("crown",keyString);
                }else {
                    map.put("crown",keys);
                }
            }
        }
        return  chatLogList;
    }

    @Override
    public Result say(ChatMsg msg, Channel channel){
        // 获取是否参加公会, 消息是否为空
        String guildId = GuildChannelRel.userGuild.get(msg.getSenderId());
        if (StringUtils.isEmpty(msg.getMsg()) || StringUtils.isEmpty(guildId)){
            return null;
        }
        //获取用户信息
        User redisUser = (User) redisUtils.get(channel.id().asLongText());
        User user = userMapper.selectUserByUid(redisUser.getId());

        if (user.getIsSay() == 0){
            return null;
        }
        if (guildId.equals(user.getMid())){
            return null;
        }

        String  day = DateUtils.format(new Date(),"YMMd");
        // 花神级别
        List<String> midsList  = Arrays.asList(deceasedMids);
        int isBirthday;
        Map<String,Object> paranMap = new HashMap<>();
        paranMap.put("mid",msg.getMid());
        paranMap.put("day",day);
        // 已故的明星不显示生日帽
        if (midsList.contains(user.getMid())){
            isBirthday = guildBannerMapper.getIsBirthday(paranMap);
        }else {
            isBirthday = 0;
        }

        int keys = 0;
        String keyString = "" ;
        List rankList = new ArrayList();
        if (isBirthday > 0 ){
            keys = 44;
        }else {
            String threeRanks = guildWeekRankMapper.getInfoForWs();
            String[] ranks = threeRanks.split(",");
            // 要优化看看php源代码把
            */
/**
 * $three_ranks = Db::name('guild_week_rank')->order('id desc')->value('three_ranks');
 * $crown = explode(',', $three_ranks);
 * $keys = array_search($mid, $crown);
 * $keys = (false === $keys) ? 0 : ($keys + 1) . ($keys + 1);
 *//*

            rankList = Arrays.asList(ranks);
            for (int i=0;i< ranks.length;i++){
                if (msg.getMid() == ranks[i]){
                    keys = i;
                }
            }
            if (rankList.contains(msg.getMid())){
                keyString = keys + 1 + "" + keys +1;
            }else {
                keys =0;
            }
        }
        //  todo 过滤一些敏感词汇

        Map<String,Object> dataMap = new HashMap<>();
        if (StringUtils.isEmpty(user.getNickname())) {user.setNickname("神秘粉丝");}
        dataMap.put("nickName",user.getNickname());
        if (StringUtils.isEmpty(user.getHeadImg())) {user.setNickname("/image/no-head.png");}
        dataMap.put("img",user.getHeadImg());
        // todo 换行 nl2br(htmlspecialchars($message['data']['content'])),
        dataMap.put("content", HtmlUtil.htmlEncode(msg.getMsg()));
        dataMap.put("crateTime",DateUtils.format(new Date(),"HH:mm:ss"));
        // crown 对应value 既可以是String 也可以是int
        if (rankList.contains(msg.getMid())){
            dataMap.put("crown",keyString);
        }else {
            dataMap.put("crown",keys);
        }
        if (StringUtils.isNotEmpty(user.getBadge())) {
            dataMap.put("badge",user.getBadge().split(","));
        }else {
            dataMap.put("badge",null);
        }
        dataMap.put("mark",user.getId());
        dataMap.put("god_level",user.getGodLevel());
        dataMap.put("type",1);


        // 公会留言信息加入缓存
        long id = guildMsgPushToRedis(msg.getMid(),user.getId(),dataMap);
        dataMap.put("id",id);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("type",msg);
        resultMap.put("data",dataMap);

        return Result.ok(resultMap);
    }

    private long guildMsgPushToRedis(String mid,Integer uid, Map map){
        String name = "guild_msg_queue_" + mid;
        long id = redisUtils.incr("guild_msg_queue_id");
        redisUtils.lpush(name,map);
        String userMsgTimeName = "user_msg_time_" + mid + "_" + uid;
        redisUtils.set(userMsgTimeName,DateUtils.format(new Date(),"YMMd"),
                24*60*60);
        long len = redisUtils.lLen(name);
        while (len > 100){
             redisUtils.rpop(name);
             len --;
        }
        return id;
    }
    @Override
    public Result sayWorld(ChatMsg msg, Channel channel) {
        //  处理type
        Integer type = msg.getType()==null ? 1:msg.getType();
        // 获取是否参加公会, 消息是否为空
        String guildId = GuildChannelRel.userGuild.get(msg.getSenderId());
        if (StringUtils.isEmpty(msg.getMsg()) || StringUtils.isEmpty(guildId)){
            return null;
        }

        String replaceBlank = msg.getMsg().replace(" ","");
        msg.setMsg(replaceBlank);
        User redisUser = (User) redisUtils.get(channel.id().asLongText());
        User user = userMapper.selectUserByUid(redisUser.getId());
        Integer speaker = user.getSpeaker();
        boolean a =  speaker < 3 && type == 2;
        boolean b =  speaker < 999 && type == 3;
        boolean c = (user.getIsSay() == 0);

        if(a || b || c){
            return null;
        }

        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> dataMap = new HashMap<>();
        resultMap.put("type","sayworld");

        String guildName = materialMapper.getNameById(Integer.valueOf(msg.getMid()));
        String day = DateUtils.format(new Date(),"YMMd");
        //  todo 判断是否生日
        int isBirthday = 1;
        if (user == null){
            return null;
        }

        int keys = 0;
        String keyString = "" ;
        List rankList = new ArrayList();
        if (isBirthday > 0 ){
            keys = 44;
        }else {
            String threeRanks = guildWeekRankMapper.getInfoForWs();
            String[] ranks = threeRanks.split(",");
            // 要优化看看php源代码把
            */
/**
 * $three_ranks = Db::name('guild_week_rank')->order('id desc')->value('three_ranks');
 * $crown = explode(',', $three_ranks);
 * $keys = array_search($mid, $crown);
 * $keys = (false === $keys) ? 0 : ($keys + 1) . ($keys + 1);
 *//*

            rankList = Arrays.asList(ranks);
            for (int i=0;i< ranks.length;i++){
                if (msg.getMid() == ranks[i]){
                    keys = i;
                }
            }
            if (rankList.contains(msg.getMid())){
                keyString = keys + 1 + "" + keys +1;
            }else {
                keys =0;
            }
        }

        // 过滤内容
        dataMap.put("guildname",guildName);
        if (StringUtils.isEmpty(user.getNickname())) {user.setNickname("神秘粉丝");}
        dataMap.put("nickName",user.getNickname());
        if (StringUtils.isEmpty(user.getHeadImg())) {user.setNickname("/image/no-head.png");}
        dataMap.put("img",user.getHeadImg());
        dataMap.put("content", HtmlUtil.htmlEncode(msg.getMsg()));
        dataMap.put("crateTime",DateUtils.format(new Date(),"HH:mm:ss"));
        if (rankList.contains(msg.getMid())){
            dataMap.put("crown",keyString);
        }else {
            dataMap.put("crown",keys);
        }
        dataMap.put("type",type);

        // 插入guild_speaker 表
        GuildSpeaker guildSpeaker = new GuildSpeaker();
        guildSpeaker.setUid(user.getId());
        guildSpeaker.setHeadImg(user.getHeadImg());
        guildSpeaker.setGuildname(guildName);
        guildSpeaker.setNickname(user.getNickname());
        guildSpeaker.setContent(msg.getMsg());
        guildSpeaker.setCreateTime((int) (System.currentTimeMillis()/1000));
        guildSpeaker.setMid(Integer.valueOf(msg.getMid()));

        guildSpeakerMapper.insertSelective(guildSpeaker);
        int needSpeaker = 3;
        if (type == 3 ){
            needSpeaker = 999;
            GuildSupperSpeakerCount speakerCount = guildSupperSpeakerCountMapper.selectByUid(user.getId());
            if (speakerCount == null){
                GuildSupperSpeakerCount guildSupperSpeakerCount = new GuildSupperSpeakerCount();
                guildSupperSpeakerCount.setUid(user.getId());
                guildSupperSpeakerCount.setNum(1);
                guildSupperSpeakerCountMapper.insertSelective(guildSupperSpeakerCount);
            }else {
                guildSupperSpeakerCountMapper.updateNum(speakerCount.getId());
            }
        }
        Map<String,Object> speakerMap = new HashMap<>();
        speakerMap.put("id",user.getId());
        speakerMap.put("$needSpeaker",needSpeaker);
        userMapper.updateSpeaker(speakerMap);

        resultMap.put("data",dataMap);
        //todo flush 给前端
        return Result.ok(resultMap);

    }

    @Override
    public Result stealflower(ChatMsg msg, Channel channel) {
        User redisUser = (User) redisUtils.get(channel.id().asLongText());
        String mid = msg.getMid();

        if(redisUser == null || msg.getCount() <=0 || Integer.valueOf(mid) <= 0 ){
            return null;
        }
        Map<String,Object> resultMap = new HashMap<>(2);
        resultMap.put("type","loading");

        Map<String,Object> dataMap = resolveData(redisUser,Integer.valueOf(mid),msg);
        dataMap.put("type",2);

        resultMap.put("data",dataMap);
        // todo flush 前端
        return null;
    }


    @Override
    public Result sendFlower(ChatMsg msg, Channel channel) {
        User redisUser = (User) redisUtils.get(channel.id().asLongText());
        String mid = msg.getMid();

        if(redisUser == null || msg.getCount() <=0 || Integer.valueOf(mid) <= 0 ){
            return null;
        }
        Integer type = msg.getType() == null ?1:msg.getType();

        Map<String,Object> resultMap = new HashMap<>(2);
        resultMap.put("type","loading");
        Map<String,Object> dataMap = resolveData(redisUser,Integer.valueOf(mid),msg);

        dataMap.put("type",1);
        // todo say to group  发给前端

        Map<String,Object> sendDataMap = new HashMap<>();
        Map<String,Object> resultSendDataMap = new HashMap<>();
        resultSendDataMap.put("type","largeflowernotice");
        sendDataMap.put("nickName",redisUser.getNickname());
        sendDataMap.put("img",redisUser.getHeadImg());
        sendDataMap.put("count",msg.getCount());
        sendDataMap.put("uname",dataMap.get("uname"));
        if (msg.getCount() >= 6666 && msg.getCount() < 5000000){
            String currentUserMid = GuildChannelRel.userGuild.get(msg.getSenderId());
            if (StringUtils.isEmpty(currentUserMid)){
                return null;
            }
            sendDataMap.put("mid",currentUserMid);
            sendDataMap.put("type",1);
            resultSendDataMap.put("data",sendDataMap);
            // todo say to group
        } else if (msg.getCount() > 5000000){
            sendDataMap.put("type",type);
            if (type == 2){
                GiftLogCount giftLogCount = giftLogCountMapper.selectByUid(redisUser.getId());
                if (giftLogCount == null){
                    GiftLogCount giftLogCount1 = new GiftLogCount();
                    giftLogCount1.setUid(redisUser.getId());
                    giftLogCount1.setNum(1);
                     giftLogCountMapper.insertSelective(giftLogCount1);
                }else{
                    giftLogCountMapper.updateGiftLogCount(giftLogCount.getId());
                }
            }
            // todo 全世界刷屏
        }
        return null;
    }

    private Map<String,Object> resolveData(User redisUser,Integer mid,ChatMsg msg){
        User user = userMapper.selectUserByUid(redisUser.getId());
        Material material = materialMapper.getStealFlowerMaterial(Integer.valueOf(mid));

        String name  =materialMapper.getNameById(Integer.valueOf(user.getMid()));
        Map<String,Object> dataMap = new HashMap<>();
        formatUserData(user,dataMap);
        dataMap.put("id",material.getId());
        dataMap.put("uname",name);
        dataMap.put("count",msg.getCount());
        dataMap.put("name",msg.getCount());
        dataMap.put("createTime",DateUtils.format(new Date(),"HH:mm:ss"));
        return  dataMap;
    }

    private void formatUserData(User user,Map dataMap){
        if (StringUtils.isEmpty(user.getNickname())) {user.setNickname("神秘粉丝");}
        dataMap.put("nickName",user.getNickname());
        if (StringUtils.isEmpty(user.getHeadImg())) {user.setNickname("/image/no-head.png");}
    }


    @Override
    public void join(ChatMsg msg, Channel channel) {
        if (StringUtils.isEmpty(msg.getMid())){
              return;
        }
        String mid = msg.getMid();
        User rediUser = (User) redisUtils.get(channel.id().asLongText());
        if (rediUser == null){
            return;
        }
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> dataMap = new HashMap<>();
        resultMap.put("type","msg");
        dataMap.put("nickName",rediUser.getNickname());
        dataMap.put("type",2);
        resultMap.put("data",dataMap);

        // todo 返回前端
        return ;
    }


}
*/
